//
//  ExerDetailVc.m
//  CareRingApp
//
//  Created by Linktop on 2023/7/17.
//  锻炼详情

#import "ExerDetailVc.h"
#import <QMUIKit/QMUIKit.h>
#import <Masonry/Masonry.h>
#import "UIViewController+Custom.h"
#import "ConfigModel.h"
#import "DeviceCenter.h"
#import "DBExercise.h"

#import "SRDeviceInfo+description.h"
#import "ValueQuarView.h"
#import "NotificationNameHeader.h"
#import "DBHistoryDataSr03.h"
#import "ExecDrawLineView.h"
#import <DateTools/DateTools.h>

@interface ExerDetailVc ()<SRBleScanProtocal, SRBleDataProtocal>

@property(strong, nonatomic)ValueQuarView *durationVs;

@property(strong, nonatomic)ValueQuarView *minHrVs, *avgHrVs, *maxHrVs;
@property(strong, nonatomic)QMUIButton *endExerBtn;

@property(strong, nonatomic) ExecDrawLineView *drawView;

@property(strong, nonatomic)NSNumber *maxValue ,* minValue, *avgValue;

@property(assign, nonatomic)BOOL isSyncing;


@property(weak, nonatomic)NSTimer *timer;
//@property(strong, nonatomic) ReadyDrawObj *drawObj;


@end

@implementation ExerDetailVc
{
    CGFloat _quar_corner_radius;
}

-(instancetype)init
{
    if (self = [super init]) {
        _quar_corner_radius = 8.0f;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // 睡眠计算完毕
    [self.navigationItem setTitle:[self.exerObj stringForExerType]];
    [self arrowback:nil];
    self.drawView = [[ExecDrawLineView alloc]init];
    
    [self initUI];
    
    [DeviceCenter instance].appDataDelegate = self;
    [DeviceCenter instance].sRappScanDelegate = self;
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(notifyExerciseDataSyncFinish:) name:NOTI_NAME_UPDATE_EXERCISE_DATA_FIN object:nil];
}

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    self.drawView.exerObj = self.exerObj;
    [self.drawView startDraw];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self setStartBtnState:[DeviceCenter instance].isBleConnected];
    
    self.endExerBtn.hidden = self.exerObj.isEnd;
    [self.durationVs updateText:[self.exerObj durationString:YES]];
    
    [self queryPoints];
    
 
    
    if (!self.exerObj.isEnd) {
        if (self.timer.isValid) {
            [self.timer invalidate];
        }
        WEAK_SELF
        self.timer = [NSTimer scheduledTimerWithTimeInterval:60 repeats:YES block:^(NSTimer * _Nonnull timer) {
            STRONG_SELF_NOT_CHECK
            if (!strongSelf) {
                [timer invalidate];
                return;
            }
            
            if (strongSelf.exerObj.isEnd) {
                // 结束了
                [timer invalidate];
                // 同步数据
                [strongSelf manualSyncData];
            }
            
            [strongSelf.durationVs updateText:[strongSelf.exerObj durationString:YES] ];
            
        }];
    }

}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    if (self.timer.isValid) {
        [self.timer invalidate];
    }
    
}

-(void)queryPoints {
    WEAK_SELF
    [self.exerObj queryPoints:^(NSMutableArray<ExercisePoint *> * _Nonnull points) {
        STRONG_SELF
        
        if (!points.count) {
            return;
        }
        
        __block int max = points.firstObject.value.intValue;
        __block int min = points.firstObject.value.intValue;
        __block float avg = 0;
        [points enumerateObjectsUsingBlock:^(ExercisePoint * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            NSNumber *value = obj.value;
            if (value.intValue > max) {
                max = value.intValue;
            }
            if (value.intValue < min) {
                min = value.intValue;
            }
            avg += value.intValue;
            
            
        }];
        if (points.count) {
            avg /= points.count;
        }

        strongSelf.drawView.exerObj = strongSelf.exerObj;
        
        strongSelf.drawView.maxValue = @(max);
        strongSelf.drawView.minValue = @(min);
        strongSelf.drawView.avgValue = @(avg);

        [strongSelf.drawView startDraw];
        
        [strongSelf.maxHrVs updateText:[NSString stringWithFormat:@"%d", max]];
        [strongSelf.minHrVs updateText:[NSString stringWithFormat:@"%d", min]];
        [strongSelf.avgHrVs updateText:[NSString stringWithFormat:@"%d", (int)avg]];
        
        
        NSInteger sumStepIncrease = 0;
        NSInteger lastStep = points.firstObject.step.integerValue;
        for (int i = 0; i < points.count; i++) {
            NSInteger increase = points[i].step.integerValue - lastStep;
            if (increase >= 0) {
                sumStepIncrease += increase;
            }
            lastStep = points[i].step.integerValue;
        }
        
        
        // calc burn calo, For example, assume the user is 1.7 meters tall and weighs 60kg
        float calo =  [strongSelf.exerObj calcBurnCaloByBodyHeight:1.7 BodyWeight:60 InsreaseStep:sumStepIncrease];
        DebugNSLog(@"Burn calo: %@", [NSString stringWithFormat:@"%.2f %@", calo, _L(L_UNIT_CAL)]);
        
        
    }];
}

-(void)notifyExerciseDataSyncFinish:(NSNotification *)noti {

    [[LTPHud Instance] hideHud];
    self.isSyncing = NO;
    [self queryPoints];
}

-(void)setStartBtnState:(BOOL)bleConnected {
    if (bleConnected) {
        self.endExerBtn.enabled = YES;
        self.endExerBtn.backgroundColor = UIColor.redColor;
    } else {
        self.endExerBtn.enabled = NO;
        self.endExerBtn.backgroundColor = UIColor.lightGrayColor;
    }
}



-(void)initUI
{
    [self.view addSubview:self.durationVs ];
    
    UIView *drawCnt = [UIView new];
    [self.view addSubview:drawCnt];
    
    [self.durationVs mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.height.equalTo(@70);
        make.top.equalTo(self.view.mas_top).offset(10);
        make.width.equalTo(@130);
    }];

    
    UILabel *hrTitlelbl = [UILabel new];
    hrTitlelbl.text = _L(L_EXER_HERATRATES);
    hrTitlelbl.textColor = UIColor.whiteColor;
    hrTitlelbl.font = [UIFont systemFontOfSize:18];
    [self.view addSubview:hrTitlelbl];
    [hrTitlelbl mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.durationVs.mas_bottom).offset(8);
        make.height.greaterThanOrEqualTo(@35);
        make.leading.equalTo(drawCnt.mas_leading).offset(20);
    }];
    
 
    [drawCnt mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.view);
        make.top.equalTo(hrTitlelbl.mas_bottom).offset(5);
        make.height.equalTo(@250);
    }];
    [drawCnt addSubview:self.drawView];
    [self.drawView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.top.bottom.equalTo(drawCnt);
    }];
    
    UIView *bottomCnt = [UIView new];
    [self.view addSubview:bottomCnt];
    [bottomCnt mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.view);
        make.top.equalTo(drawCnt.mas_bottom).offset(10);
    }];
    
    [bottomCnt addSubview:self.minHrVs ];
    [bottomCnt addSubview:self.avgHrVs ];
    [bottomCnt addSubview:self.maxHrVs ];
    
    NSArray<ValueQuarView *> *array = @[self.minHrVs, self.avgHrVs, self.maxHrVs];
    [array mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:10 leadSpacing:10 tailSpacing:10];
//    [array mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedItemLength:10 leadSpacing:20 tailSpacing:20];
    [array mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(self.durationVs.mas_height);
        make.top.bottom.equalTo(bottomCnt);
        
    }];
    
    [self.view addSubview: self.endExerBtn];
    
    [self.endExerBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.centerX.equalTo(self.view.mas_centerX);
        make.height.equalTo(@44);
        make.top.equalTo(bottomCnt.mas_bottom).offset(35);
        make.width.equalTo(self.view.mas_width).multipliedBy(2/3.0);
    }];
    
   
    
}

-(void)endExer:(QMUIButton *)btn {
    

    // 是否同步中

    WEAK_SELF
    [self showAlertWarningWithTitle:_L(L_TIPS) Msg:_L(L_TIP_END_EARLY) btnOk:_L(L_OK) OkBLk:^{
        STRONG_SELF

        [strongSelf manualSyncData];


    } CancelBtn:_L(L_CANCEL) CancelBlk:^{
        STRONG_SELF
        
        
    } Compelete:nil];
    
    
    
}

-(void)manualSyncData {
    [[DeviceCenter instance].sdk functionShutdownSportMode]; // 下发停止
    
    [[LTPHud Instance] showHudLasting:3 Text:_L(L_SYNCING_DATA)]; // 同步数据中
    self.isSyncing = YES;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[DeviceCenter instance] startSyncDeviceCacheData];
    });
   
}


#pragma mark --蓝牙

- (void)srBleDeviceBatteryLevel:(NSInteger)batteryLevel IsCharging:(BOOL)isCharging {
    
}

- (void)srBleDeviceDidReadyForReadAndWrite:(nonnull SRBLeService *)service {
    [self setStartBtnState:YES];

}

- (void)srBleDeviceInfo:(nonnull SRDeviceInfo *)devInfo {
    
}

- (void)srBleDeviceRealtimeSteps:(nonnull NSNumber *)steps IsDeviceFix:(BOOL)isDeviceFixed{
    
}

- (void)srBleDeviceRealtimeTemperature:(nonnull NSNumber *)temperature {
    
}

- (void)srBleDidConnectPeripheral:(nonnull SRBLeService *)service {
}

- (void)srBleDidDisconnectPeripheral:(nonnull SRBLeService *)service {
    [self setStartBtnState:NO];
    
    [[LTPHud Instance] hideHud];
    
    WEAK_SELF
    if (self.isSyncing) {
        [self showAlertWarningWithTitle:_L(L_TIPS) Msg:_L(L_TIPS_DEVICE_BLE_DISCED) btnOk:_L(L_OK) OkBLk:^{
            STRONG_SELF
            //
            [strongSelf.navigationController popViewControllerAnimated:YES];
            
        } CancelBtn:nil CancelBlk:nil Compelete:nil];
    }
    
    

}

-(void)srBleCmdExcute:(EXCUTED_CMD)cmd Succ:(BOOL)isSucc Reason:(CMD_EXECTE_ERROR_REASON)reason
{
    if (cmd == EXCUTED_CMD_SPORT_MODE) {
        
        if (!isSucc) {
            NSString *string = [SRDeviceInfo descryOfErrorReason:reason];
            if (string.length) {
                [self showAlertWarningWithTitle:_L(L_TIPS) Msg:string btnOk:_L(L_OK) OkBLk:^{
                    
                } CancelBtn:nil CancelBlk:nil Compelete:nil];
            }
            [[LTPHud Instance] hideHud];
        } else {
            // 保存
            WEAK_SELF
            self.exerObj.endDate = [NSDate date];
            [self.exerObj updateEndDate:^(BOOL succ) {
                STRONG_SELF
                // 更新运动模式时间
                [strongSelf.durationVs updateText:[strongSelf.exerObj durationString:YES]];

            }];
            
            self.endExerBtn.hidden = YES;
        }
       
        
        return;
    }
    
    if (cmd == EXCUTED_CMD_HIS_DATA && !isSucc) { // 同步数据
//        [[LTPHud Instance] hideHud];
        
        NSString *str = [SRDeviceInfo descryOfErrorReason:reason];
        if (str.length) {
            [[LTPHud Instance] showText:str Lasting:2];
        }
        WEAK_SELF
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
           STRONG_SELF
            [strongSelf.navigationController popViewControllerAnimated:YES];
            
        });
        
    }
    
}




- (void)srBleHistoryDataTimeout {
    
}



- (void)srBleMeasureDuration:(NSInteger)seconds {
    
}

- (void)srBleOEMAuthResult:(BOOL)authSucceddful {
    
}



- (void)srBleSN:(nonnull NSString *)sn SnData:(nonnull NSData *)snData {
    
}

- (void)srBleSOShappen {
    
}

- (void)srBlesSOSData:(float)temperature HeartRate:(NSInteger)hr BloodOxygen:(NSInteger)bloodOxygen {
    
}

#pragma mark --lazy

- (QMUIButton *)endExerBtn
{
    if (!_endExerBtn) {
        _endExerBtn = [[QMUIButton alloc]init];
        _endExerBtn.backgroundColor = UIColor.lightGrayColor;
        
        _endExerBtn.cornerRadius = ITEM_CORNOR_RADIUS;
        [_endExerBtn setTitle:_L(L_TITLE_EARLY_END) forState:UIControlStateNormal];
        
        [_endExerBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        [_endExerBtn addTarget:self action:@selector(endExer:) forControlEvents:UIControlEventTouchUpInside];
        _endExerBtn.enabled = NO; // 初始不可用
    }
    return _endExerBtn;
}
-(ValueQuarView *)durationVs
{
    if (!_durationVs) {
        _durationVs = [[ValueQuarView alloc]init];
        _durationVs.titleLbl.text = _L(L_EXERC_DURATION); // 锻炼时间
        _durationVs.valueLbl.text = NONE_VALUE;//@"70 bmp";
        _durationVs.layer.cornerRadius = _quar_corner_radius;
    }
    return _durationVs;
}


-(ValueQuarView *)minHrVs
{
    if (!_minHrVs) {
        _minHrVs = [[ValueQuarView alloc]init];
        _minHrVs.titleLbl.text = _L(L_TITLE_EXER_MIN_HR); //
        _minHrVs.valueLbl.text = NONE_VALUE;//@"70 bmp";
        _minHrVs.layer.cornerRadius = _quar_corner_radius;
    }
    return _minHrVs;
}

-(ValueQuarView *)avgHrVs
{
    if (!_avgHrVs) {
        _avgHrVs = [[ValueQuarView alloc]init];
        _avgHrVs.titleLbl.text = _L(L_TITLE_EXER_AVG_HR);//@"平均心率"; //
        _avgHrVs.valueLbl.text = NONE_VALUE;//@"70 bmp";
        _avgHrVs.layer.cornerRadius = _quar_corner_radius;
    }
    return _avgHrVs;
}
-(ValueQuarView *)maxHrVs
{
    if (!_maxHrVs) {
        _maxHrVs = [[ValueQuarView alloc]init];
        _maxHrVs.titleLbl.text = _L(L_TITLE_EXER_MAX_HR);//@"最大心率"; //
        _maxHrVs.valueLbl.text = NONE_VALUE;//@"70 bmp";
        _maxHrVs.layer.cornerRadius = _quar_corner_radius;
    }
    return _maxHrVs;
}




-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
